from constraint import Problem
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
from constraint import Problem, ExactSumConstraint

# 使用约束求解器生成测试用例的函数
def generate_test_cases(num_cases):
    problem = Problem()
    # 假设我们需要找到两个整数x和y
    problem.addVariable('x', range(1, 11))
    problem.addVariable('y', range(1, 11))
    # 添加约束条件：x + y > 10
    problem.addConstraint(lambda x, y: x + y > 10)
    # variables = ['x', 'y']
    # domains = {var: range(1, 11) for var in variables}
    # problem.addVariables(variables, domains)
    # # 添加约束条件
    # problem.addConstraint(lambda x, y: x + y > 10)
    solutions = problem.getSolutions()

    # 如果解决方案的数量小于所需的案例数量，则返回所有解决方案
    if len(solutions) < num_cases:
        return solutions

    # 否则返回前num_cases个解决方案
    return solutions[:num_cases]

# 数据准备
def generate_data(num_samples):
    X = np.random.rand(num_samples, 2) * 10  # 生成x和y的随机值
    y = (X[:, 0] + X[:, 1] > 10).astype(int)  # 计算是否满足约束
    return X, y

# 训练SVM模型
def train_svm(X_train, y_train):
    scaler = StandardScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    svm = SVC(kernel='linear')
    svm.fit(X_train_scaled, y_train)
    return svm, scaler


# 主程序
def main():
    # 生成训练数据
    num_samples = 100
    X, y = generate_data(num_samples)

    # 划分训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    # 训练SVM模型
    svm, scaler = train_svm(X_train, y_train)

    # 评估模型
    X_test_scaled = scaler.transform(X_test)
    y_pred = svm.predict(X_test_scaled)
    print("Accuracy:", accuracy_score(y_test, y_pred))

    # 生成测试用例
    test_cases = generate_test_cases(10)
    for case in test_cases:
        print(case)

    # 使用SVM筛选测试用例
    test_cases_matrix = np.array([[case['x'], case['y']] for case in test_cases])
    test_cases_scaled = scaler.transform(test_cases_matrix)
    selected_cases = svm.predict(test_cases_scaled)
    for case, selection in zip(test_cases, selected_cases):
        if selection == 1:
            print(f"Selected Case: {case}")


if __name__ == "__main__":
    main()